package com.brave.base;

import java.security.MessageDigest;

/**
 * @UserName: BraveKing-wy
 * @DateTime:2019/1/5 9:22
 * @Description:
 **/
public class MD5Kit
{
    private static final String[] hexDigits = new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    public MD5Kit() {
    }

    public static String MD5Encode(String source) {
        String result = null;

        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(source.getBytes("UTF-8"));
            result = byteArrayToHexString(messageDigest.digest());
        } catch (Exception var3) {
            var3.printStackTrace();
        }
        return result;
    }

    public static String MD5Encode(String source, String encoding, boolean uppercase) {
        String result = null;

        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(source.getBytes(encoding));
            result = byteArrayToHexString(messageDigest.digest());
        } catch (Exception var5) {
            var5.printStackTrace();
        }

        return uppercase ? result.toUpperCase() : result;
    }

    private static String byteArrayToHexString(byte[] bytes) {
        StringBuilder stringBuilder = new StringBuilder();
        byte[] var2 = bytes;
        int var3 = bytes.length;

        for(int var4 = 0; var4 < var3; ++var4) {
            byte tem = var2[var4];
            stringBuilder.append(byteToHexString(tem));
        }

        return stringBuilder.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (b < 0) {
            n = 256 + b;
        }

        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }
}